﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using Wwtfly.BBS.Framework.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Wwtfly.BBS.BackModels.Models;

namespace Wwtfly.DBUtility
{
    /// <summary>
    /// 参数  
    /// </summary>
    public class DBParamsUtility
    {

        /// <summary>
        ///向 Command 添加 分页参数
        /// </summary>
        /// <param name="pageParams">分页参数</param>
        /// <param name="database">Database</param>
        /// <param name="dbCommand">DbCommand</param>
        public static void CreatePageParams(PageParams pageParams, Database database, DbCommand dbCommand)
        {
            database.AddInParameter(dbCommand, "@PageIndex", DbType.Int32, pageParams.PageIndex);
            database.AddInParameter(dbCommand, "@PageSize", DbType.Int32, pageParams.PageSize);
            database.AddInParameter(dbCommand, "@SortFieldName", DbType.String, pageParams.SortFieldName);
            database.AddInParameter(dbCommand, "@SortDirection", DbType.Int32, (int)pageParams.SortDirection);
            database.AddOutParameter(dbCommand, "@TotalCount", DbType.Int32, 32);
        }

        /// <summary>
        ///向 Command 添加 分页参数
        /// </summary>
        /// <param name="pageParams">分页参数</param>
        /// <param name="database">Database</param>
        /// <param name="dbCommand">DbCommand</param>
        public static void CreatePageParamsOfNotOutTotalCount(PageParams pageParams, Database database, DbCommand dbCommand)
        {
            database.AddInParameter(dbCommand, "@PageIndex", DbType.Int32, pageParams.PageIndex);
            database.AddInParameter(dbCommand, "@PageSize", DbType.Int32, pageParams.PageSize);
            database.AddInParameter(dbCommand, "@SortFieldName", DbType.String, pageParams.SortFieldName);
            database.AddInParameter(dbCommand, "@SortDirection", DbType.Int32, (int)pageParams.SortDirection);
        }

        /// <summary>
        /// 从集合中 获取 总记录数
        /// </summary>
        /// <param name="dbCommand">DbCommand</param>
        /// <returns></returns>
        public static long GetTotalCount<T>(IList<T> list) where T : BaseModel
        {
            if (list != null && list.Count > 0)
            {
                BaseModel bm = list[0];
                return bm.TotalCount;
            }
            return 0;
        }

        /// <summary>
        /// 从输出参数 获取 总记录数
        /// </summary>
        /// <param name="dbCommand">DbCommand</param>
        /// <returns></returns>
        public static int GetTotalCount(DbCommand dbCommand)
        {
            return Convert.ToInt32(dbCommand.Parameters["@TotalCount"].Value);
        }
    }
}